<template>
  <div class="com-container">
    <div class="com-chart" ref="hot_ref"></div>
    <span class="iconfont arr-l" @click="toLeft" :style="comStyle"
      >&#xe6ef;</span
    >
    <span class="iconfont arr-r" @click="toRight" :style="comStyle"
      >&#xe6ed;</span
    >
    <span class="cat-name" :style="comStyle">{{ catName }}</span>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import《组件名称》from'《组件路径》';
import { mapState } from "vuex";
import { getThemeValue } from "@/utils/theme_utils.js";
export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  props: {},
  data() {
    //这里存放数据
    return {
      chartEntity: null,
      allData: null,
      index: 0,
      fontSize: 0,
    };
  },
  //计算属性:类似于data概念,有缓存效果,用于不经常修改的数据
  computed: {
    catName() {
      if (!this.allData) {
        return "";
      } else {
        return this.allData[this.index].name;
      }
    },
    comStyle() {
      return {
        fontSize: this.fontSize + "px",
        color: getThemeValue(this.theme).titleColor,
      };
    },
    //监控data中的数据变化
    ...mapState(["theme"]),
  },
  // 监控data中的数据变化
  watch: {
    theme() {
      // 销毁当前图表
      this.chartEntity.dispose();
      this.initChart();
      this.screenAdapter();
      this.updateChart();
    },
  },
  //方法集合
  methods: {
    initChart() {
      this.chartEntity = this.$echarts.init(this.$refs.hot_ref, this.theme);
      let option = {
        title: {
          text: "热销商品",
          left: 20,
          top: 20,
        },
        legend: {
          top: "15%",
          icon: "circle",
        },
        tooltip: {
          show: true,
          formatter: (arg) => {
            let lv2Catecory = arg.data.children;
            let total = 0;
            lv2Catecory.forEach((e) => (total += e.value));
            let retStr = "";
            lv2Catecory.forEach((e) => {
              retStr += `
              ${e.name}: ${parseInt((e.value / total) * 100)}%<br/>
              `;
            });
            return retStr;
          },
        },
        series: [
          {
            type: "pie",
            label: {
              show: false,
            },
            emphasis: {
              label: {
                show: true,
              },
              labelLine: {
                show: false,
              },
            },
          },
        ],
      };
      this.chartEntity.setOption(option);
    },
    getData(ret) {
      // let { data: ret } = await this.$http.get("hotproduct");
      // ret.sort((a, b) => b.value - a.value);
      this.allData = ret;
      // 刷新图表
      this.updateChart();
    },
    updateChart() {
      let seriesArr = this.allData[this.index].children.map((item) => {
        return {
          name: item.name,
          value: item.value,
          children: item.children,
        };
      });
      let dataOption = {
        legend: {
          data: seriesArr.name,
        },
        series: [
          {
            data: seriesArr,
          },
        ],
      };
      this.chartEntity.setOption(dataOption);
    },
    // 根据屏幕大小调整分辨率
    screenAdapter() {
      let title_font_size = (this.$refs.hot_ref.offsetWidth / 100) * 3.6;
      this.fontSize = title_font_size;
      let adapterOption = {
        title: {
          textStyle: {
            fontSize: title_font_size,
          },
        },
        legend: {
          itemWidth: title_font_size,
          itemHeight: title_font_size,
          itemGep: title_font_size / 2,
          textStyle: {
            fontSize: title_font_size / 1.5,
          },
        },
        series: [
          {
            radius: title_font_size * 4.5,
            center: ["50%", "55%"],
          },
        ],
      };
      this.chartEntity.setOption(adapterOption);
      this.chartEntity.resize();
    },
    toLeft() {
      this.index--;
      if (this.index < 0) {
        this.index = this.allData.length - 1;
      }
      this.updateChart();
    },
    toRight() {
      this.index++;
      if (this.index > this.allData.length - 1) {
        this.index = 0;
      }
      this.updateChart();
    },
  },
  beforeCreate() {}, //生命周期-创建之前
  created() {
    this.$socket.registerCallBack("hot", this.getData);
  }, //生命周期-创建完成（可以访问当前this实例）
  beforeMount() {}, //生命周期-挂载之前
  mounted() {
    this.initChart();
    // this.getData();
    this.$socket.send({
      action: "getData",
      socketType: "hot",
      chartName: "hotproduct",
      value: "",
    });

    // 不要在函数中加(), 否则只会调用一次
    window.addEventListener("resize", this.screenAdapter);
    // 加载完成后自动适配分辨率
    this.screenAdapter();
  }, //生命周期-挂载完成（可以访问DOM元素）
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
  beforeUpdate() {}, //生命周期-更新之前
  updated() {}, //生命周期-更新之后
  beforeDestroy() {}, //生命周期-销毁之前
  destroyed() {
    this.$socket.unRegisterCallBack("hot", this.getData);
  }, //生命周期-销毁完成
};
</script>

<style lang="less" scoped>
.arr-l,
.arr-r {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  color: #fff;
  cursor: pointer;
}
.arr-l {
  left: 10%;
}
.arr-r {
  right: 10%;
}
.cat-name {
  position: absolute;
  right: 15%;
  bottom: 15%;
  color: #fff;
}
</style>